package com.file.system.controller.system;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.file.system.entity.dict.NoticeType;
import com.file.system.entity.res.BaseCode;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.res.DataPage;
import com.file.system.entity.system.WebNotice;
import com.file.system.plugin.validated.SQLInjectionValidation;
import com.file.system.plugin.websocket.WebSocketServer;
import com.file.system.service.system.IWebNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;

import static cn.hutool.core.util.ObjectUtil.isNotEmpty;


/**
 * 通知公告
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/web/notice")
public class WebNoticeController {

    @Autowired
    private IWebNoticeService service;

    /**
     * 查询通知公告分页
     *
     * @param pageIndex 页数
     * @param pageSize  每页条数
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/page/{pageIndex}/{pageSize}")
    public CommonResult<DataPage<List<WebNotice>>> select(@PathVariable
                                                          @Min(value = 1, message = "页数最小1")
                                                          Integer pageIndex,
                                                          @PathVariable
                                                          @Min(value = 1, message = "每页条数最小1")
                                                          @Max(value = 100, message = "每页条数最大100")
                                                          Integer pageSize,
                                                          @RequestBody @Validated WebNotice webNotice
    ) {
        QueryWrapper<WebNotice> query = new QueryWrapper<>();
        query.orderByDesc("a.id");
        //查询状态为0的数据
        query.eq("a.is_del", 0);
        //查询名称
        query.like(isNotEmpty(webNotice.getName()), "a.name", webNotice.getName());
        //查询内容
        query.like(isNotEmpty(webNotice.getContent()), "a.content", webNotice.getContent());
        //查询通知类型
        query.eq(isNotEmpty(webNotice.getDictNoticeType()), "a.dict_notice_type", webNotice.getDictNoticeType());
        //查询是否开启
        query.eq(isNotEmpty(webNotice.getDictOnOff()), "a.dict_on_off", webNotice.getDictOnOff());
        //查询编号
        query.eq(ObjectUtil.isNotNull(webNotice.getNum()), "a.num", webNotice.getNum());
        //查询结束日期
        query.eq(isNotEmpty(webNotice.getEndDate()), "a.end_date", webNotice.getEndDate());
        //查询集合
        DataPage<List<WebNotice>> dp = service.page(pageIndex, pageSize, query);
        return CommonResult.ok().setResult(dp);
    }


    /**
     * 通过ids查询通知公告集合
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/listByIds")
    public CommonResult<List<WebNotice>> listByIds(@RequestBody List<Long> ids) {
        //查询集合
        List<WebNotice> list = service.listByIds(ids);
        return CommonResult.ok().setResult(list);
    }

    /**
     * 查询所有非删除状态通知公告
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/listAll")
    public CommonResult<List<WebNotice>> listAll() {
        //查询集合
        List<WebNotice> list = service.listAll();
        return CommonResult.ok().setResult(list);
    }


    /**
     * 通过id查询通知公告
     *
     * @param id 通知公告id
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/id/{id}")
    public CommonResult<WebNotice> selectById(@PathVariable
                                              @Min(value = 1, message = "id长度最小1")
                                              Long id) {
        //查询集合
        WebNotice webNotice = service.getById(id);
        return CommonResult.ok().setResult(webNotice);
    }



    /**
     * 通过id删除通知公告
     *
     * @param id id
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/remove/{id}")
    public CommonResult removeById(@PathVariable
                            @Min(value = 1, message = "id长度最小1")
                            @SQLInjectionValidation(fieldName = "id")
                            Long id) {
        boolean state = service.removeById(id);
        //返回
        return CommonResult.check(state);
    }


    /**
     * 通过id编辑通知公告
     *
     * @param webNotice 通知公告
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/updateById")
    public CommonResult<WebNotice> updateById(@RequestBody @Validated(WebNotice.update.class) WebNotice webNotice) {
        //通知截止日期设置为空公告循环次数设置为空
        if (NoticeType.notice.val.equals(webNotice.getDictNoticeType())) {
            webNotice.setEndDate(null);
        } else if (NoticeType.pub.val.equals(webNotice.getDictNoticeType())) {
            webNotice.setNum(null);
        }
        //编辑修改
        boolean state = service.updateById(webNotice);
        return CommonResult.check(state).setResult(webNotice);
    }


    /**
     * 添加通知公告
     *
     * @param webNotice 通知公告
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/save")
    public CommonResult<WebNotice> save(@RequestBody @Validated(WebNotice.add.class) WebNotice webNotice) {

        boolean state = service.save(webNotice);
        // 判断是否保存成功
        if (!state) {
            return CommonResult.fail().setResult(webNotice);
        }
        // 根据通知类型发送消息
        switch (webNotice.getDictNoticeType()) {
            case "notice":
                // 获取通知数量，如果没有设置，则默认为1
                int num = webNotice.getNum() == null ? 1 : webNotice.getNum();
                // 发送通知消息
                WebSocketServer.broadCastInfo(BaseCode.Common.MSG_NOTICE, webNotice, num);
                break;

            case "public":
                // 发送公共消息
                WebSocketServer.broadCastInfo(BaseCode.Common.MSG_PUBLIC, webNotice);
                break;
            default:
                break;
        }

        return CommonResult.ok().setResult(webNotice);
    }
}

